import request from '../../util/request';
import { addCotolog } from '../../api'


const catalog = {
  state: {
    projectId: 0,
    catalogs: [],
    power: ''
  },
  mutations: {
    setCatalog: (state, catalogs) => {
      state.catalogs = catalogs;
    },
    setProjectId: (state, projectId) => {
      state.projectId = projectId;
    },
    appendRoot: (state, catalog) => {
      state.catalogs.push(catalog);
    },
    setPower: (state, power) => {
      state.power = power;
    }
  },
  actions: {
    loadPower: (context,id) => {
      request({
        url: '/userproject/' + id,
        method: 'get'
      }).then(function (resp) {
        if (resp.errmsg === 'ok') {
          context.commit("setPower", resp.data.power);
        }
      });
    },
    loadCatalog: (context, id) => {
      context.commit("setProjectId", id);
      request({
        url: "/catalog/project/" + id,
        method: "get"
      }).then(function (resp) {
        if (resp.errmsg === "ok") {
          context.commit('setCatalog', resp.data);
        }
      }).catch(function (e) {
        console.log(e);
      });
    },
    appendRoot: (context, name) => {
      addCotolog(name, context.state.projectId, 0).then(function (resp) {
        if (resp.errmsg === "ok") {
          context.commit('appendRoot', resp.data);
        }
      }).catch(function (e) {
        console.log(e);
      });
    },
    append: (context, payload) => {
      addCotolog(payload.name, context.state.projectId, payload.data.id).then(function (resp) {
        if (resp.errmsg === "ok") {
          if (!payload.data.children) {
            payload.data.children = new Array();
          }
          payload.data.children.push(resp.data);
        }
      }).catch(function (e) {
        console.log(e);
      });
    }
  }
}

export default catalog
